package ldh.im.client.controller;

import ldh.im.client.config.RsaService;
import ldh.im.client.util.HttpUtil;
import ldh.im.client.util.JsonUtil;
import ldh.im.client.validate.ParamCheckUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FxLoginController {

    private static final String IM_HOST = "http://localhost:8080/client/imLogin";

    @Value("${im.tenantCode}")
    private String tenantCode;

    @Resource
    private RsaService rsaService;

    /**
     *
     * @param userName  登录用户名
     * @param password  登录密码
     * @return
     */
    @RequestMapping(path="/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam("name") String userName, @RequestParam("password") String password) throws Exception {
        ParamCheckUtil.notEmpty(userName, "用户名不能为空");
        ParamCheckUtil.notEmpty(password, "密码不能为空");
        Map<String, Object> data = new HashMap();
        data.put("name", userName);
        data.put("password", password);
        String json = JsonUtil.toJson(data);
        String encodeBody = rsaService.encryptByPrivateKey(json);

        String encodeImCode = rsaService.encryptByPublicKey(tenantCode);
        Map<String, Object> params = new HashMap();
        params.put("data", encodeBody);
        params.put("imCode", encodeImCode);
        String result = HttpUtil.post(IM_HOST, params);
        return result;
    }

    @GetMapping(path="/encode")
    public String encode(@RequestParam("msg") String msg) throws Exception {
        return rsaService.encryptByPrivateKey(msg);
    }

    @GetMapping(path="/decode")
    public String decode(@RequestParam("msg") String msg) throws Exception {
        return rsaService.decryptByPublicKey(msg);
    }
}
